package com.example.support.profile.service;

import java.time.Duration;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.support.profile.dao.ProfileDao;
import com.example.support.profile.model.Profile;
import com.example.support.redis.RedisHelper;

@org.springframework.stereotype.Service
public class ProfileService {

	private ProfileDao profileDao;

	public ProfileService(ProfileDao profileDao) {
		this.profileDao = profileDao;
	}

	// ========== Profile ==========

	public Profile findProfileByName(String name) {
		String cacheKey = cacheKey(name);
		Profile profile = JSON.parseObject(RedisHelper.get(cacheKey), Profile.class);
		if (profile == null) {
			profile = findProfileByName0(name);
			RedisHelper.setex(cacheKey, Duration.ofMinutes(30).getSeconds(), JSON.toJSONString(profile));
		}
		return profile;
	}

	private Profile findProfileByName0(String name) {
		return profileDao.selectOne(new QueryWrapper<Profile>()
				.eq("config_key", name)
				);
	}

	public static String cacheKey(String name) {
		return "cache0:profile:" + name;
	}

}
